package com.talkyun.openx.ocean.provider;

import com.talkyun.ocean.model.Provider;
import com.talkyun.utils.HostUtils;
import com.talkyun.utils.Reflector;

import javax.servlet.ServletContext;
import java.util.Date;

public class ProviderManager {
    private HostUtils host = HostUtils.get();

    public Provider getServiceProviderFromTomcat(ServletContext tomcatServletContext) {
        Provider provider = new Provider();
        provider.setAddress(host.getLocalIp());
        provider.setAppId(this.getAppId());
        provider.setProtocol("http");
        provider.setPort(getTomcatPort(tomcatServletContext));
        // update by registry
        provider.setEndpoint("?");
        provider.setLastModify(new Date());
        return provider;
    }

    private String getAppId() {
        return host.getEnvSetting("app.id", "app_id");
    }

    private int getTomcatPort(ServletContext tomcatServletContext) {
        String path = "context.context.parent.parent.service.connectors[0].port";
        Object port = Reflector.getValueByPath(tomcatServletContext, path);
        if (!(port instanceof Integer)) {
            return 0;
        }
        return (Integer) port;
    }
}